//
//  ApplyMenuViewController.swift
//  LongTermInsurance
//
//  Created by DYD on 2018/11/27.
//  Copyright © 2018 HeChao. All rights reserved.
//

import UIKit
import ObjectMapper

class ApplyMenuViewController: BaseViewController {
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var idLabel: UILabel!
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var personInfoView: UIView!
    @IBOutlet weak var lifeStateView: UIView!
    @IBOutlet weak var healthView: UIView!
    @IBOutlet weak var inabilityView: UIView!
    
    lazy var healthViewController = ApplyHealthViewController()
    lazy var stateViewController = ApplyStateViewController()
    lazy var personInfoViewController = ApplyPersonInfoViewController()
    lazy var inabilityViewController = ApplyInabilityViewController()
    
    var oldApplyID: Int!
    
    deinit {
        print("")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "申请"
        clean()
        if let info = MyselfSingleton.shared.userInfo {
            avatarImageView.image = info.sex == "男" ? R.image.gender_male() : R.image.gender_female()
            nameLabel.text = info.name
            idLabel.text = info.personNum
        }
        
        let viewTap1 = UITapGestureRecognizer(target: self, action: #selector(viewTap(_:)))
        personInfoView.addGestureRecognizer(viewTap1)
        
        let viewTap2 = UITapGestureRecognizer(target: self, action: #selector(viewTap(_:)))
        lifeStateView.addGestureRecognizer(viewTap2)
        let viewTap3 = UITapGestureRecognizer(target: self, action: #selector(viewTap(_:)))
        healthView.addGestureRecognizer(viewTap3)
        let viewTap4 = UITapGestureRecognizer(target: self, action: #selector(viewTap(_:)))
        inabilityView.addGestureRecognizer(viewTap4)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", style: .plain, target: self, action: #selector(goBack))
        
        getOldApplyData()
    }
    
    func clean() {
        let infoVC = self.personInfoViewController
        infoVC.cleanData()
        
        let inabilityPath = CDArchiverPath.inabilityStateFilePath
        if FileManager.default.fileExists(atPath: inabilityPath)
        {
            do {
                try FileManager.default.removeItem(atPath: inabilityPath)
            }
            catch{
                CDUtility.log(error)
            }
        }
        
        let statePath = CDArchiverPath.liveStateFilePath
        if FileManager.default.fileExists(atPath: statePath)
        {
            do {
                try FileManager.default.removeItem(atPath: statePath)
            }
            catch{
                CDUtility.log(error)
            }
        }
        let healthPath = CDArchiverPath.healthStateFilePath
        if FileManager.default.fileExists(atPath: healthPath)
        {
            do {
                try FileManager.default.removeItem(atPath: healthPath)
            }
            catch{
                CDUtility.log(error)
            }
        }
        UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.homeCareChooseInfoKey)
        UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.orgCareChooseInfoKey)
        UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.userUploadPhotos) // 图片
        UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.zoneChooseInfoKey)
        UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.streetChooseInfoKey)
    }
    
    func getOldApplyData() {
        guard let oldID = oldApplyID else{
            return
        }
        let paramString = "<sqdh>\(oldID)</sqdh>"
        CDUtility.showHud()
        NetworkingHandle.fetchNetworkData(method: "SelectApplyInfo", paramString: paramString, success: {[weak self] (dict) in
            CDUtility.hidHud()
            
            guard let array0 = (dict["SQ01"] as! String).convertToObject() as? [[String: Any]],let dict0 = array0.first else {
                return
            }
            guard let array1 = (dict["SQ02"] as! String).convertToObject() as? [[String: Any]],let dict1 = array1.first else {
                return
            }
            guard let array2 = (dict["SQ03"] as! String).lowercased().convertToObject() as? [[String: Any]] else {
                return
            }
            
            // 存图片
            let photoArray = Mapper<ApplyPhotoRemoteModel>().mapArray(JSONArray: array2)
            var newPhotoArray = [ApplyPhotoModel]()
            for remotePhoto in photoArray {
                let localeModel = ApplyPhotoModel()
                localeModel.isRemote = true
                localeModel.uploaded = true
                localeModel.name = remotePhoto.name
//                localeModel.type = localeModel.name
                newPhotoArray.append(localeModel)
            }
            let jsonArray = newPhotoArray.compactMap { model -> NSDictionary? in
                return [
                    "name": model.name,
//                    "data": model.data,
                    "isRemote": model.isRemote,
                    "uploaded": model.uploaded
                ]
            }
            UserDefaults.standard.set(jsonArray, forKey: CDUserDefaultKey.userUploadPhotos)
            
            // 健康状况
            let plistPath = Bundle.main.url(forResource: "apply_health", withExtension: "plist")!
            let dataDict = NSArray(contentsOf: plistPath) as! [[String: Any]]
            let healthStateDataArray = Mapper<QuestionModel>().mapArray(JSONArray: dataDict)
            
            for model in healthStateDataArray {
                if model.canEnterSupply && model.enterInfo.count > 0 {
                    if let data = dict0[model.enterInfo] as? String {
                        model.enterDetail = data
                    } else if let data = dict1[model.enterInfo] as? String {
                        model.enterDetail = data
                    } else if let data = dict0[model.enterInfo] as? Int {
                        model.enterDetail = "\(data)"
                    } else if let data = dict1[model.enterInfo] as? Int {
                        model.enterDetail = "\(data)"
                    }
                }
                for item in model.items {
//                    if model.multiChoose {
//
//                    }
                    if let value = dict0[item.uploadInfo] {
                        if let num = StringValue(value: value) {
                            if model.multiChoose {
                                if IntValue(value: num ) == 1 {
                                    item.selected = true
                                    item.uploadDetail = "1"
                                }
                            } else {
                                if num == item.uploadDetail {
                                    item.selected = true
                                }
                            }
                        }
                    } else if let value = dict1[item.uploadInfo] {
                        if let num = StringValue(value: value) {
                            if model.multiChoose {
                                if IntValue(value: num ) == 1 {
                                    item.selected = true
                                    item.uploadDetail = "1"
                                }
                            } else {
                                if num == item.uploadDetail {
                                    item.selected = true
                                }
                            }
                        }
                        //                        item.uploadDetail = "\(num)"
                    }
                }
            }
            let path = CDArchiverPath.healthStateFilePath
            let json = healthStateDataArray.toJSON()
            let dict = NSMutableDictionary()
            dict.setValue(json, forKey: "health")
            let _ = dict.write(toFile: path, atomically: false)
            
            // 失能信息
            let inPlistPath = Bundle.main.url(forResource: "apply_inability", withExtension: "plist")!
            let inDataDict = NSArray(contentsOf: inPlistPath) as! [[String: Any]]
            let inabilityStateDataArray = Mapper<QuestionModel>().mapArray(JSONArray: inDataDict)
            
            for model in inabilityStateDataArray {
                if model.canEnterSupply && model.enterInfo.count > 0 {
                    if let data = dict0[model.enterInfo] as? String {
                        model.enterDetail = data
                    } else if let data = dict1[model.enterInfo] as? String {
                        model.enterDetail = data
                    } else if let data = dict0[model.enterInfo] as? Int {
                        model.enterDetail = "\(data)"
                    } else if let data = dict1[model.enterInfo] as? Int {
                        model.enterDetail = "\(data)"
                    }
                }
                for item in model.items {
                    //                    if model.multiChoose {
                    //
                    //                    }
                    if let value = dict0[item.uploadInfo] {
                        if let num = StringValue(value: value) {
                            if model.multiChoose {
                                if IntValue(value: num ) == 1 {
                                    item.selected = true
                                    item.uploadDetail = "1"
                                }
                            } else {
                                if num == item.uploadDetail {
                                    item.selected = true
                                }
                            }
                        }
                    } else if let value = dict1[item.uploadInfo] {
                        if let num = StringValue(value: value) {
                            if model.multiChoose {
                                if IntValue(value: num ) == 1 {
                                    item.selected = true
                                    item.uploadDetail = "1"
                                }
                            } else {
                                if num == item.uploadDetail {
                                    item.selected = true
                                }
                            }
                        }
                    }
                }
            }
            let inPath = CDArchiverPath.inabilityStateFilePath
            let inJson = inabilityStateDataArray.toJSON()
            let inDict = NSMutableDictionary()
            inDict.setValue(inJson, forKey: "inability")
            let _ = inDict.write(toFile: inPath, atomically: false)
            
            let zoneNum = dict1["QHXH"] as? String ?? ""
            let streetNum = dict1["JDXH"] as? String ?? ""
            self?.inabilityViewController.fileChooseView.getData(zoneNum) {
                // 服务方式1机构护理2居家护理
                let serviceType = IntValue(value: dict1["FWLB"] ?? "")
                if serviceType == 1 {
                    let id = IntValue(value: dict1["HLJG"] ?? "")
                    for model in self?.inabilityViewController.fileChooseView.orgCareArray ?? [CareOrgModel]() {
                        if model.id == id {
                            self?.inabilityViewController.fileChooseView.chooseORGModel = model
                            self?.inabilityViewController.fileChooseView.updateChoose()
                            UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.homeCareChooseInfoKey)
                            UserDefaults.standard.set(model.toJSON(), forKey: CDUserDefaultKey.orgCareChooseInfoKey)
                            break
                        }
                    }
                } else if serviceType == 2 {
                    let id = IntValue(value: dict1["JJJG"] ?? "")
                    for model in self?.inabilityViewController.fileChooseView.homeCareArray ?? [HomeCareModel]() {
                        if model.id == id {
                            self?.inabilityViewController.fileChooseView.chooseHomeModel = model
                            self?.inabilityViewController.fileChooseView.updateChoose()
                            UserDefaults.standard.set(model.toJSON(), forKey: CDUserDefaultKey.homeCareChooseInfoKey)
                            UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.orgCareChooseInfoKey)
                            break
                        }
                    }
                }
                
                for model in self?.inabilityViewController.fileChooseView.zoneArray ?? [ZoneModel]() {
                    if model.zoneNum == zoneNum {
                        self?.inabilityViewController.fileChooseView.chooseZoneModel = model
                        self?.inabilityViewController.fileChooseView.updateChoose()
                        UserDefaults.standard.set(model.toJSON(), forKey: CDUserDefaultKey.zoneChooseInfoKey)
                        break
                    }
                }
                
                for model in self?.inabilityViewController.fileChooseView.streetArray ?? [StreetModel]() {
                    if model.streetNum == streetNum {
                        self?.inabilityViewController.fileChooseView.chooseStreetModel = model
                        self?.inabilityViewController.fileChooseView.updateChoose()
                        UserDefaults.standard.set(model.toJSON(), forKey: CDUserDefaultKey.streetChooseInfoKey)
                        break
                    }
                }
            }
            // 生活
            self?.stateViewController.getData {
                
                let lifeStateDataArray = self!.stateViewController.dataSource
                for model in lifeStateDataArray {
                    if model.canEnterSupply && model.enterInfo.count > 0 {
                        if let data = dict0[model.enterInfo] as? String {
                            model.enterDetail = data
                        } else if let data = dict1[model.enterInfo] as? String {
                            model.enterDetail = data
                        } else if let data = dict0[model.enterInfo] as? Int {
                            model.enterDetail = "\(data)"
                        } else if let data = dict1[model.enterInfo] as? Int {
                            model.enterDetail = "\(data)"
                        }
                    }
                    for item in model.items {
                        //                    if model.multiChoose {
                        //
                        //                    }
                        if let value = dict0[item.uploadInfo] {
                            if let num = StringValue(value: value) {
                                if model.multiChoose {
                                    if IntValue(value: num ) == 1 {
                                        item.selected = true
                                        item.uploadDetail = "1"
                                    }
                                } else {
                                    if num == item.uploadDetail {
                                        item.selected = true
                                    }
                                }
                            }
                        } else if let value = dict1[item.uploadInfo] {
                            if let num = StringValue(value: value) {
                                if model.multiChoose {
                                    if IntValue(value: num ) == 1 {
                                        item.selected = true
                                        item.uploadDetail = "1"
                                    }
                                } else {
                                    if num == item.uploadDetail {
                                        item.selected = true
                                    }
                                }
                            }
                        }
                    }
                }
                let lifePath = CDArchiverPath.liveStateFilePath
                let lifeJson = lifeStateDataArray.toJSON()
                let lifeDict = NSMutableDictionary()
                lifeDict.setValue(lifeJson, forKey: "live")
                let _ = lifeDict.write(toFile: lifePath, atomically: false)
                
            }
            
            // 个人信息
            let peronInfoVC = self!.personInfoViewController
            
            peronInfoVC.fetchDataIfNeed {
                if let data = StringValue(value: dict0["GDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.teleApply.detailText.value = data
                    peronInfoVC.teleApply.save("teleApply")
                } else if let data = StringValue(value: dict1["GDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.teleApply.detailText.value = data
                    peronInfoVC.teleApply.save("teleApply")
                }
                
                if let data = StringValue(value: dict0["HJDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.homeTownApply.detailText.value = data
                    peronInfoVC.homeTownApply.save("homeTownApply")
                } else if let data = StringValue(value: dict1["HJDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.homeTownApply.detailText.value = data
                    peronInfoVC.homeTownApply.save("homeTownApply")
                }
                
                if let data = StringValue(value: dict0["HYZK"] ?? ""), data.count > 0 {
                    let data = IntValue(value: data)
                    for model in peronInfoVC.marriedApply.chooseArray {
                        if model.id == data {
                            peronInfoVC.marriedApply.chooseModel = model
                            peronInfoVC.marriedApply.detailText.value = model.name
                            peronInfoVC.marriedApply.save("marriedApply")
                            break
                        }
                    }
                } else if let data = StringValue(value: dict1["HYZK"] ?? ""), data.count > 0 {
                    let data = IntValue(value: data)
                    for model in peronInfoVC.marriedApply.chooseArray {
                        if model.id == data {
                            peronInfoVC.marriedApply.chooseModel = model
                            peronInfoVC.marriedApply.detailText.value = model.name
                            peronInfoVC.marriedApply.save("marriedApply")
                            break
                        }
                    }
                }
                
                //            requestData["JHGX"] = helpRelationApply.chooseModel.id
                if let data = StringValue(value: dict0["JHGX"] ?? ""), data.count > 0 {
                    let data = IntValue(value: data)
                    for model in peronInfoVC.helpRelationApply.chooseArray {
                        if model.id == data {
                            peronInfoVC.helpRelationApply.chooseModel = model
                            peronInfoVC.helpRelationApply.detailText.value = model.name
                            peronInfoVC.helpRelationApply.save("helpRelationApply")
                            break
                        }
                    }
                } else if let data = StringValue(value: dict1["JHGX"] ?? ""), data.count > 0 {
                    let data = IntValue(value: data)
                    for model in peronInfoVC.helpRelationApply.chooseArray {
                        if model.id == data {
                            peronInfoVC.helpRelationApply.chooseModel = model
                            peronInfoVC.helpRelationApply.detailText.value = model.name
                            peronInfoVC.helpRelationApply.save("helpRelationApply")
                            break
                        }
                    }
                }
                
                
                //            requestData["JHRGDDH"] = helpTeleApply.detailText.value
                if let data = StringValue(value: dict0["JHRGDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.helpTeleApply.detailText.value = data
                    peronInfoVC.helpTeleApply.save("helpTeleApply")
                } else if let data = StringValue(value: dict1["JHRGDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.helpTeleApply.detailText.value = data
                    peronInfoVC.helpTeleApply.save("helpTeleApply")
                }
                //            requestData["JHRDZ"] = helpMailAddressApply.detailText.value
                if let data = StringValue(value: dict0["JHRDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailAddressApply.detailText.value = data
                    peronInfoVC.helpMailAddressApply.save("helpMailAddressApply")
                } else if let data = StringValue(value: dict1["JHRDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailAddressApply.detailText.value = data
                    peronInfoVC.helpMailAddressApply.save("helpMailAddressApply")
                }
                //            requestData["JHRM"] = helpNameApply.detailText.value
                if let data = StringValue(value: dict0["JHRM"] ?? ""), data.count > 0 {
                    peronInfoVC.helpNameApply.detailText.value = data
                    peronInfoVC.helpNameApply.save("helpNameApply")
                } else if let data = StringValue(value: dict1["JHRM"] ?? ""), data.count > 0 {
                    peronInfoVC.helpNameApply.detailText.value = data
                    peronInfoVC.helpNameApply.save("helpNameApply")
                }
                //            requestData["JHRYDDH"] = helpMobile.detailText.value
                if let data = StringValue(value: dict0["JHRYDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMobile.detailText.value = data
                    peronInfoVC.helpMobile.save("helpMobile")
                } else if let data = StringValue(value: dict1["JHRYDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMobile.detailText.value = data
                    peronInfoVC.helpMobile.save("helpMobile")
                }
                //            requestData["JLSLQFS"] = getMethod.chooseModel.id
                if let data = StringValue(value: dict0["JLSLQFS"] ?? ""), data.count > 0 {
                    let data = IntValue(value: data)
                    for model in peronInfoVC.getMethod.chooseArray {
                        if model.id == data {
                            peronInfoVC.getMethod.chooseModel = model
                            peronInfoVC.getMethod.detailText.value = model.name
                            peronInfoVC.getMethod.save("getMethod")
                            break
                        }
                    }
                } else if let data = StringValue(value: dict1["JLSLQFS"] ?? ""), data.count > 0 {
                    let data = IntValue(value: data)
                    for model in peronInfoVC.getMethod.chooseArray {
                        if model.id == data {
                            peronInfoVC.getMethod.chooseModel = model
                            peronInfoVC.getMethod.detailText.value = model.name
                            peronInfoVC.getMethod.save("getMethod")
                            break
                        }
                    }
                }
                //            requestData["JZDZ"] = liveAddress.detailText.value
                if let data = StringValue(value: dict0["JZDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.liveAddress.detailText.value = data
                    peronInfoVC.liveAddress.save("liveAddress")
                } else if let data = StringValue(value: dict1["JZDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.liveAddress.detailText.value = data
                    peronInfoVC.liveAddress.save("liveAddress")
                }
                //            requestData["QSDZ"] = helpMailAddressApply.detailText.value
                if let data = StringValue(value: dict0["QSDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailAddressApply.detailText.value = data
                    peronInfoVC.helpMailAddressApply.save("helpMailAddressApply")
                } else if let data = StringValue(value: dict1["QSDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailAddressApply.detailText.value = data
                    peronInfoVC.helpMailAddressApply.save("helpMailAddressApply")
                }
                //            requestData["QSRM"] = helpMailReceiverApply.detailText.value
                if let data = StringValue(value: dict0["QSRM"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailReceiverApply.detailText.value = data
                    peronInfoVC.helpMailReceiverApply.save("helpMailReceiverApply")
                } else if let data = StringValue(value: dict1["QSRM"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailReceiverApply.detailText.value = data
                    peronInfoVC.helpMailReceiverApply.save("helpMailReceiverApply")
                }
                //            requestData["QSRSJHM"] = helpSMSApply.detailText.value
                if let data = StringValue(value: dict0["QSRSJHM"] ?? ""), data.count > 0 {
                    peronInfoVC.helpSMSApply.detailText.value = data
                    peronInfoVC.helpSMSApply.save("helpSMSApply")
                } else if let data = StringValue(value: dict1["QSRSJHM"] ?? ""), data.count > 0 {
                    peronInfoVC.helpSMSApply.detailText.value = data
                    peronInfoVC.helpSMSApply.save("helpSMSApply")
                }
                //            requestData["QSYB"] = helpMailCodeApply.detailText.value
                if let data = StringValue(value: dict0["QSYB"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailCodeApply.detailText.value = data
                    peronInfoVC.helpMailCodeApply.save("helpMailCodeApply")
                } else if let data = StringValue(value: dict1["QSYB"] ?? ""), data.count > 0 {
                    peronInfoVC.helpMailCodeApply.detailText.value = data
                    peronInfoVC.helpMailCodeApply.save("helpMailCodeApply")
                }
                
                if let data = StringValue(value: dict0["HKDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.homeTownApply.detailText.value = data
                    peronInfoVC.homeTownApply.save("homeTownApply")
                } else if let data = StringValue(value: dict1["HKDZ"] ?? ""), data.count > 0 {
                    peronInfoVC.homeTownApply.detailText.value = data
                    peronInfoVC.homeTownApply.save("homeTownApply")
                }
                
                
                //            requestData["SBHM"] = shebaoIDApply.detailText.value
                //            if let data = StringValue(value: dict0["SBHM"] ?? ""), data.count > 0 {
                //                peronInfoVC.shebaoIDApply.detailText.value = data
                //                peronInfoVC.shebaoIDApply.save("helpMailCodeApply")
                //            } else if let data = StringValue(value: dict1["SBHM"] ?? ""), data.count > 0 {
                //                peronInfoVC.shebaoIDApply.detailText.value = data
                //                peronInfoVC.shebaoIDApply.save("helpMailCodeApply")
                //            }
                
                //            requestData["SFZH"] = idApply.detailText.value
                //            if let data = StringValue(value: dict0["SFZH"] ?? ""), data.count > 0 {
                //                peronInfoVC.idApply.detailText.value = data
                //                peronInfoVC.idApply.save("idApply")
                //            } else if let data = StringValue(value: dict1["SFZH"] ?? ""), data.count > 0 {
                //                peronInfoVC.idApply.detailText.value = data
                //                peronInfoVC.idApply.save("idApply")
                //            }
                
                //            requestData["YDDH"] = mobileApply.detailText.value
                if let data = StringValue(value: dict0["YDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.mobileApply.detailText.value = data
                    peronInfoVC.mobileApply.save("mobileApply")
                } else if let data = StringValue(value: dict1["YDDH"] ?? ""), data.count > 0 {
                    peronInfoVC.mobileApply.detailText.value = data
                    peronInfoVC.mobileApply.save("mobileApply")
                }
            }
            

        }) {
            CDUtility.hidHud()
            print("")
        }
    }
    
    @objc func viewTap(_ tap: UITapGestureRecognizer) {
        if tap.view == personInfoView {
            navigationController?.pushViewController(personInfoViewController, animated: true)
        } else if tap.view == inabilityView {
            navigationController?.pushViewController(inabilityViewController, animated: true)
        } else if tap.view == lifeStateView {
            navigationController?.pushViewController(stateViewController, animated: true)
        } else {
            navigationController?.pushViewController(healthViewController, animated: true)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    @objc func goBack() {
        let alert = UIAlertController(title: "是否放弃本次提交", message: nil, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "放弃", style: .default, handler: { (action) in
            self.navigationController?.popViewController(animated: true)
        })
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancel)
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    @IBAction func submitAction(_ sender: UIButton) {
        
        // 判断
        let peronInfoVC = personInfoViewController
        if !peronInfoVC.enterFull() {
            makeToast("请先完善-个人资料")
            return
        }
        
        var lifeStateDataArray = [QuestionModel]()
        let lifePath = CDArchiverPath.liveStateFilePath
        if FileManager.default.fileExists(atPath: lifePath) {
            if let dict = NSDictionary(contentsOfFile: lifePath) {
                if let array = dict["live"] as? [[String: Any]]{
                    lifeStateDataArray = Mapper<QuestionModel>().mapArray(JSONArray: array)
                }
            }
        }
        if lifeStateDataArray.isEmpty {
            makeToast("请先完善-生活状况")
            return
        }
        
        var healthStateDataArray = [QuestionModel]()
        let healthPath = CDArchiverPath.healthStateFilePath
        if FileManager.default.fileExists(atPath: healthPath) {
            if let dict = NSDictionary(contentsOfFile: healthPath) {
                if let array = dict["health"] as? [[String: Any]]{
                    healthStateDataArray = Mapper<QuestionModel>().mapArray(JSONArray: array)
                }
            }
        }
        if healthStateDataArray.isEmpty {
            makeToast("请先完善-就医健康")
            return
        }
        
        var inabilityStateDataArray = [QuestionModel]()
        let inPath = CDArchiverPath.inabilityStateFilePath
        if FileManager.default.fileExists(atPath: inPath) {
            if let dict = NSDictionary(contentsOfFile: inPath) {
                if let array = dict["inability"] as? [[String: Any]]{
                    inabilityStateDataArray = Mapper<QuestionModel>().mapArray(JSONArray: array)
                }
            }
        }
        if inabilityStateDataArray.isEmpty {
            makeToast("请先完善-失能信息")
            return
        }
        
        
        // 个人资料
        var personInfoData = peronInfoVC.requestData()
        
        // 生活状况
        var lifeStateData = [String: Any]()
        for model in lifeStateDataArray {
            if model.canEnterSupply {
                lifeStateData[model.enterInfo] = model.enterDetail
            }
            for item in model.items {
                if item.selected {
                    lifeStateData[item.uploadInfo] = item.uploadDetail
                }
            }
        }
        lifeStateData["JZHJCS"] = 0
        lifeStateData["JZHJXY"] = 0
        if let care = lifeStateData["SFZL"] as? String, care == "0" {
            lifeStateData["ZLRY"] = 0
        }
        
        // 就医健康
        var healthData = [String: Any]()
        for model in healthStateDataArray {
            if model.canEnterSupply {
                healthData[model.enterInfo] = model.enterDetail
            }
            for item in model.items {
                if item.selected {
                    healthData[item.uploadInfo] = item.uploadDetail
                } else {
                    if model.multiChoose {
                        healthData[item.uploadInfo] = 0
                    }
                }
            }
        }
        healthData["JYZFFS"] = 0
        healthData["JYZFQT"] = ""
        healthData["CDHM"] = 0
        healthData["CDQT"] = 0
        healthData["CDQTMC"] = ""
        healthData["CHBZ"] = 0
        healthData["DDBZ"] = 0
        healthData["GSBZ"] = 0
        healthData["JYFS"] = 0
        healthData["JYFSQT"] = ""
        healthData["JZBS"] = 0
        healthData["JSJB"] = 0
        healthData["YCBZ"] = 0
        healthData["YSBZ"] = 0
        healthData["YWSBZ"] = 0
        healthData["ZSBZ"] = 0
        healthData["QTBZ"] = 0
        
        // 失能信息
        var inabilityData = [String: Any]()
        for model in inabilityStateDataArray {
            if model.canEnterSupply {
                inabilityData[model.enterInfo] = model.enterDetail
            }
            for item in model.items {
                if item.selected {
                    inabilityData[item.uploadInfo] = item.uploadDetail
                    
                } else {
                    if model.multiChoose {
                        inabilityData[item.uploadInfo] = 0
                    }
                }
            }
        }
//        inabilityData["SNXZJB"] = 0
//        inabilityData["SNSZJB"] = 0
        
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.homeCareChooseInfoKey) as? [String: Any] {
            if let m = Mapper<HomeCareModel>().map(JSON: dict) {
                inabilityData["FWLB"] = 1 // 服务方式1机构护理2居家护理
                inabilityData["HLJG"] = m.id
                inabilityData["JJJG"] = 0
            }
        }
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.orgCareChooseInfoKey) as? [String: Any] {
            if let m = Mapper<CareOrgModel>().map(JSON: dict) {
                inabilityData["FWLB"] = 2 // 服务方式1机构护理2居家护理
                inabilityData["JJJG"] = m.id
                inabilityData["HLJG"] = 0
            }
        }
        
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.zoneChooseInfoKey) as? [String: Any] {
            if let m = Mapper<ZoneModel>().map(JSON: dict) {
                inabilityData["QHXH"] = m.zoneNum // 乡镇区划
                personInfoData["QHXH"] = m.zoneNum // 乡镇区划
            }
        }
        if let dict = UserDefaults.standard.object(forKey: CDUserDefaultKey.streetChooseInfoKey) as? [String: Any] {
            if let m = Mapper<StreetModel>().map(JSON: dict) {
                inabilityData["JDXH"] = m.streetNum // 街道区划
                personInfoData["JDXH"] = m.streetNum // 街道区划
            }
        }
        
        // 图片资源
//        var photoArray = [String]()
        var photoArray = [[String: Any]]()
        if let data = UserDefaults.standard.array(forKey: CDUserDefaultKey.userUploadPhotos) as? [[String: Any]]{
            let _ = Mapper<ApplyPhotoModel>().mapArray(JSONArray: data).map { (m) -> ApplyPhotoModel in
                if m.uploaded {
                    
//                    photoArray.append(m.fullPathName)
                    
                    let photoDict = ["AppendType": 78,
                                     "FileName": m.name,
                                     "FilePath": "../Upload/\(m.name)"] as [String : Any]
                    photoArray.append(photoDict)
                }
                return m
            }
        }
        
        var paramString =
            "<jbxx>\([personInfoData].convertToJsonString())</jbxx>" +
            "<shxx>\([lifeStateData].convertToJsonString())</shxx>" +
            "<jyxx>\([healthData].convertToJsonString())</jyxx>" +
            "<snxx>\([inabilityData].convertToJsonString())</snxx>" +
            "<fjxx>\(photoArray.convertToJsonString())</fjxx>"
        var method = "SaveApplyInfo"
        if oldApplyID != nil {
            method = "UpdateApplyInfo"
            paramString += "<sqdh>\(oldApplyID!)</sqdh>"
        }
        
        NetworkingHandle.fetchNetworkData(method: method, paramString: paramString, success: {[weak self] (dict) in
            if let code = dict["ResultCode"] as? Int,code == 0 {
                CDUtility.showMSG(message: "提交成功！")
                self?.navigationController?.popToRootViewController(animated: true)
                return
            }
            if let code = dict["ResultCode"] as? Int,code == 1 {
                if let msgString = dict["ResultMessage"] as? String {
                    CDUtility.showMSG(message: msgString)
                }
            }
        }) {
            print("")
        }
        
        
    }
    
}
